<template>
  <div class="release_wrap">
    <div class="release_title">播 放 视 频</div>
    <el-card class="release_card">
      <el-button type="primary" round icon="el-icon-arrow-left" style="margin-bottom: 40px"
        @click="jump_home">返回首页</el-button>

      <el-table stripe :data="tableData" style="width: 100%" height="600px">
        <el-table-column prop="videoName" label="视频名称" min-width="280">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="playVideo(scope.$index, scope.row)">播放</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog :modal="false" title="视频播放" :visible.sync="dialogVisible" width="40%">
      <p class="video_title">{{ videoName }}</p>
      <video :src="videoUrl" controls="controls" width="100%"></video>

    </el-dialog>
  </div>
</template>

<script>
var video = () => {
  var videoTime = document.getElementById("myvideo");
  console.log(videoTime.duration); //获取视频时长
  console.log(videoTime.currentTime); //获取视频当前播放时间
};
import { mapState } from "vuex";
import IPconfig from "./IPconfig";
const baseUrl = IPconfig.baseUrl;

export default {
  name: 'VideoPlayMerge',
  data() {
    return {
      title: "",
      videolist: "",
      //表格数据
      tableData: [],
      //弹框组件隐藏
      dialogVisible: false,
      //用于保存视频的id
      videoId: 0,
      //保存视频的名称
      videoName: '',
      videoUrl: '',
      mediaSource: null,
      sourceBuffer: null,
      chunkSize: 0,
      totalSize: 0,
    };
  },
  computed: {
    //引入vuex中state的变量，可以直接this.xxx调用到
    ...mapState(["article"]),
  },
  created() {
    this.getVideoInfo();
  },

  methods: {
    jump_home() {
      this.$router.replace('/')
    },
    getVidDur() {
      video();
    },
    //获取video表格数据
    getVideoInfo() {
      this.$axios.get(baseUrl + "/SelectVideo/table").then((res) => {
        console.log('res:', res)
        this.tableData = res.data;
      });
    },
    // 点击播放按钮
    async playVideo(i, val) {
      // 显示弹框
      this.dialogVisible = true;
      // 保存视频名字
      this.videoName = val.videoName;
      // 保存视频id
      this.videoId = val.id;
      // 发送HEAD请求获取视频的总大小
      try {
        const res = await this.$axios.get(`${baseUrl}/SelectVideo/getVideoSizeById/${this.videoId}`);
        this.totalSize = res.data;
        this.chunkSize = Math.ceil(this.totalSize / 20); // 设置分片大小为总大小的1/20

        // 创建 MediaSource 并为视频元素设置 URL
        this.mediaSource = new MediaSource();
        this.videoUrl = URL.createObjectURL(this.mediaSource);

        // 监听 MediaSource 的 sourceopen 事件，准备开始加载分片
        this.mediaSource.addEventListener('sourceopen', () => {
          this.sourceBuffer = this.mediaSource.addSourceBuffer('video/mp4; codecs="avc1.42E81E, mp4a.40.2"');
          this.sourceBuffer.addEventListener('updateend', () => { this.loadAndPlayChunks })
          this.loadAndPlayChunks(0, this.totalSize - 1); // 加载所有分片
        });
      } catch (error) {
        console.error('Failed to get video size:', error);
      }
    },

    loadAndPlayChunks(startByte, endByte) {
      const sourceBuffer = this.sourceBuffer;
      const videoId = this.videoId;

      const loadNextChunk = (nextStartByte) => {
        if (nextStartByte >= endByte) {
          return; // 已加载所有分片，退出循环
        }

        // 获取下一个分片的字节范围
        const nextEndByte = Math.min(nextStartByte + this.chunkSize - 1, endByte);

        // 获取分片数据

        this.$axios
          .get(`${baseUrl}/SelectVideo/policemen/${videoId}`, {
            headers: {
              Range: `bytes=${nextStartByte}-${nextEndByte}`,
            },
            responseType: 'arraybuffer',
          })
          .then((response) => {
            const chunk = response.data;

            // 将分片追加到 SourceBuffer


            sourceBuffer.appendBuffer(chunk)



            // 递归调用加载下一个分片
            loadNextChunk(nextEndByte + 1);
          })
          .catch((error) => {
            console.error('Failed to load video:', error);
          });

      };

      // 从第一个分片开始加载
      loadNextChunk(startByte);
    },

  },
};
</script>

<style></style>
